// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.warehouse.viewers.database;

import java.sql.Connection;
import java.util.List;

import org.dengues.commons.IDenguesSharedImage;
import org.dengues.commons.connectivity.EDatabaseType;
import org.dengues.commons.utils.ImageUtil;
import org.dengues.core.DenguesCorePlugin;
import org.dengues.core.actions.AbstractAction;
import org.dengues.core.connectivity.IConnectivityManager;
import org.dengues.core.metadata.MetadataUtils;
import org.dengues.core.resource.WarehouseResourceFactory;
import org.dengues.core.warehouse.ENavNodeType;
import org.dengues.core.warehouse.ENodeCategoryName;
import org.dengues.model.DenguesModelManager;
import org.dengues.model.database.DBTable;
import org.dengues.model.database.DatabaseDiagram;
import org.dengues.ui.prefs.connectivity.EConnectivityProperties;
import org.dengues.ui.query.TablesSelectDialog;
import org.dengues.warehouse.i18n.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 2007-12-10 qiang.zhang $
 * 
 */
public class SynchronizeDbFromConnAction extends AbstractAction {

    /**
     * Qiang.Zhang.Adolf@gmail.com SynchronizeDbFromConnAction constructor comment.
     */
    public SynchronizeDbFromConnAction() {
        super(Messages.getString("SynchronizeDbFromConnAction.syn.text")); //$NON-NLS-1$
        setImageDescriptor(ImageUtil.getDescriptor(IDenguesSharedImage.VIEW_SYNCHRONIZEDB));
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.action.Action#run()
     */
    @Override
    public void run() {
        if (pnodes != null) {
            final DatabaseDiagram diagram = (DatabaseDiagram) pnodes.get(0).getObject().getData();
            getWarehouseView();
            Job job = new Job(Messages.getString("SynchronizeDbFromConnAction.sys.joblabel")) { //$NON-NLS-1$

                @Override
                protected IStatus run(IProgressMonitor monitor) {
                    monitor.beginTask(Messages.getString("SynchronizeDbFromConnAction.sys.taskLabel"), IProgressMonitor.UNKNOWN); //$NON-NLS-1$
                    IConnectivityManager manager = DenguesCorePlugin.getDefault().getDenguesUiService().getConnectivityManager();
                    manager.getConnection(diagram.getProperties(), true, EDatabaseType.isNestedDriverFromDriver(diagram
                            .getProperties().get(EConnectivityProperties.PROP_ID_DRIVER.getPropId())));
                    final DatabaseDiagram databaseDiagram = DenguesModelManager.getDatabaseFactory().createDatabaseDiagram();
                    databaseDiagram.getProperties().put(EConnectivityProperties.PROP_ID_DATABASE.getPropId(),
                            diagram.getProperties().get(EConnectivityProperties.PROP_ID_DATABASE.getPropId()));
                    Connection connection = manager.getConnection();
                    if (connection != null) {
                        MetadataUtils.getDbTables(databaseDiagram, connection, monitor);
                        if (!monitor.isCanceled()) {

                            Display.getDefault().asyncExec(new Runnable() {

                                /*
                                 * (non-Javadoc)
                                 * 
                                 * @see java.lang.Runnable#run()
                                 */
                                public void run() {
                                    TablesSelectDialog selectDialog = new TablesSelectDialog(PlatformUI.getWorkbench()
                                            .getActiveWorkbenchWindow().getShell(), databaseDiagram);
                                    if (selectDialog.open() == TablesSelectDialog.OK) {
                                        List<DBTable> selectedTables = selectDialog.getSelectedTables();
                                        List<String> existTableNames = MetadataUtils.getExistTableNames(diagram);
                                        for (DBTable table : selectedTables) {
                                            if (!existTableNames.contains(table.getName())) {
                                                table.setDbDiagram(diagram);
                                                diagram.getDbChildren().add(table);
                                            }
                                        }
                                        MetadataUtils.autoLinkFKs(diagram);
                                        WarehouseResourceFactory.save(diagram);
                                    }
                                    refresh(pnodes.get(0));
                                }
                            });
                        }
                    }
                    monitor.done();
                    return Status.OK_STATUS;
                }

            };
            job.setUser(true);
            job.setPriority(Job.SHORT);
            job.schedule();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.actions.AbstractAction#getLevel()
     */
    @Override
    public int getLevel() {
        return 225;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.core.actions.AbstractAction#computeEnable()
     */
    @Override
    protected boolean computeEnable() {
        boolean isEnable = false;
        if (pnodes != null && pnodes.size() == 1) {
            isEnable = (ENodeCategoryName.DATABASE == pnodes.get(0).getCategoryName() || ENodeCategoryName.QUERY == pnodes.get(0)
                    .getCategoryName())
                    && ENavNodeType.ELEMENT == pnodes.get(0).getNodeType();
        }
        return isEnable;
    }
}
